#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   init_driver.py
@Time    :   2024/01/21 17:51:52
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   初始化浏览器驱动
'''

from rpa_tool.download_drive import download_chrome_driver
from rpa_tool.get_version import get_chrome_version
from common import Config

import os

__dirname = Config.BASE_PATH

# 初始化浏览器驱动，返回驱动地址
def init_chrome_driver() -> str:
    driver_path = ""
    version_osname = get_chrome_version()
    name = ""
    if version_osname["os_name"] == "Linux":
        name = "linux64"
    elif version_osname["os_name"] == "Windows":
        name = "win64"
    isExist = False
    chromedriver_path = os.path.join(__dirname, "chromedriver")
    if not os.path.exists(chromedriver_path):
        os.makedirs(chromedriver_path)
    for root, dirs, files in os.walk(chromedriver_path):
        for dir in dirs:  
            if dir == version_osname["version"]:
                for rs, ds, fs in os.walk(f"{chromedriver_path}/{dir}"):
                    for d in ds:
                        if d == f"chromedriver-{name}":
                            if name == "linux64":
                                driver_path = f"{chromedriver_path}/{dir}/chromedriver-{name}/chromedriver"
                            elif name == "win64":
                                driver_path = f"{chromedriver_path}/{dir}/chromedriver-{name}/chromedriver.exe"
                            isExist = True
                            break
                break
                                                    
    if not isExist:
        res = download_chrome_driver(f"{chromedriver_path}/{version_osname['version']}/chromedriver.zip")
        if res is None:
            if name == "linux64":
                driver_path = f"{chromedriver_path}/{version_osname['version']}/chromedriver-{name}/chromedriver"
            elif name == "win64":
                driver_path = f"{chromedriver_path}/{version_osname['version']}/chromedriver-{name}/chromedriver.exe"    
        else:
            driver_path = res
            
    return driver_path
